package com.wedo.mall.widget;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.e.library.utils.EDensityUtils;
import com.e.library.utils.EUtils;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.wedo.mall.R;
import com.wedo.mall.activity.goods.GoodsDetailActivity;
import com.wedo.mall.adapter.ShoppingAdapter;
import com.wedo.mall.entity.AttrItem;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.Shopping;
import com.wedo.mall.util.WUrl;

import java.util.ArrayList;
import java.util.List;

/**
 * 购物车
 * Created by e on 2017/7/27.
 */

public class ShoppingView extends LinearLayout{

    private int mItemHeight;
    private boolean editable = false;
    private boolean checkable = true;
    private boolean swipe = true;

    private Shopping mShopping;
    private ShoppingAdapter mShoppingAdapter;
    private ShoppingAdapter.OnObservableCheck mObservable;
    private String goods_inventory_shortage;
    private String express_type;//送货方式:0：送货上门，1：到店取货

    public ShoppingView(Context context) {
        this(context,null);
    }

    public ShoppingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public ShoppingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mItemHeight = EDensityUtils.dip2px(context,125);
        goods_inventory_shortage = context.getResources().getString(R.string.goods_inventory_shortage);
    }

    public ShoppingView shopping(Shopping shopping){
        this.mShopping = shopping;
        return this;
    }

    public ShoppingView adapter(ShoppingAdapter adapter){
        this.mShoppingAdapter = adapter;
        return this;
    }

    public ShoppingView observable(ShoppingAdapter.OnObservableCheck observable){
        this.mObservable = observable;
        return this;
    }

    private List<CheckBox> checkBoxes = new ArrayList<>();
    private CheckBox cb_agent;
    public ShoppingView agent(CheckBox checkBox){
        this.cb_agent = checkBox;
        return this;
    }

    public ShoppingView editable(boolean editable){
        this.editable = editable;
        return this;
    }

    public ShoppingView checkable(boolean checkable){
        this.checkable = checkable;
        return this;
    }

    public ShoppingView swipe(boolean swipe){
        this.swipe = swipe;
        return this;
    }

    public ShoppingView express(String express){
        this.express_type = express;
        return this;
    }

    public void goodsList(List<Goods> goodsList){
        removeAllViews();
        checkBoxes.clear();
        setOrientation(VERTICAL);
        if (EUtils.isEmpty(goodsList)){
            return;
        }

        int size = goodsList.size();
        for (int i = 0;i<size;i++){
            Goods goods = goodsList.get(i);
            View view = goods(goods,i == size-1);
            LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mItemHeight);
            this.addView(view,params);
        }
    }

    private boolean onBinding = false;
    private View goods(final Goods goods, boolean last){
        View view = LayoutInflater.from(getContext()).inflate(layout(),null);
        final SwipeMenuLayout sml_swipe = (SwipeMenuLayout)view.findViewById(R.id.sml_swipe);
        Button btn_delete = (Button) view.findViewById(R.id.btn_delete);

        final CheckBox cb_check = (CheckBox) view.findViewById(R.id.cb_check);
        ImageView iv_img = (ImageView) view.findViewById(R.id.iv_img);
        TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
        TextView tv_attr = (TextView) view.findViewById(R.id.tv_attr);
        TextView tv_price = (TextView) view.findViewById(R.id.tv_price);

        View v_divider = view.findViewById(R.id.v_divider);
        v_divider.setVisibility(last?GONE:VISIBLE);

        if(editable) {
            /**编辑*/
            tv_attr.setClickable(true);
            onEditGoods(view,goods);

        }else {
            tv_attr.setClickable(false);
            tv_attr.setOnClickListener(null);
            TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
            tv_number.setText(String.format("X%s",goods.goods_number));

            View v_express = view.findViewById(R.id.v_express);
            if(TextUtils.isEmpty(express_type)) {
                v_express.setVisibility(GONE);
            }else {
                v_express.setVisibility(goods.containsExpress(express_type)?GONE:VISIBLE);
                if (!goods.containsExpress(Goods.EXPRESS_0)){
                    /**不支持送货上门,弹出toast*/
                    Toast.makeText(getContext(),R.string.goods_delivery_unavailable_toast,Toast.LENGTH_SHORT).show();
                }
            }
        }

        tv_name.setText(goods.goods_name);
        tv_attr.setText(toAttr(goods.attrList));
        tv_price.setText(String.format("RM%s",goods.fixPrice()));

        String img = WUrl.url(goods.goods_image);
        Glide.with(getContext()).load(img)
                .error(R.drawable.place_holder_goods).placeholder(R.drawable.place_holder_goods)
                .diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_img);

        onBinding = true;
        cb_check.setChecked(goods.check);
        onBinding = false;

        if(checkable) {
            cb_check.setVisibility(VISIBLE);
            cb_agent.setVisibility(VISIBLE);
        }else {
            cb_check.setVisibility(GONE);
            cb_agent.setVisibility(GONE);
        }

        checkBoxes.add(cb_check);
        cb_check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(onBinding) {
                    return;
                }
                if (isChecked){
                    mShopping.check  = isCheckAll();
                }else {
                    mShopping.check = false;
                }
                goods.check = isChecked;
                mShoppingAdapter.notifyDataSetChanged();
                if(mObservable !=null) {
                    mObservable.onChecked(mShoppingAdapter.isCheckAll());
                }

            }
        });


        view.findViewById(R.id.rl_item).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), GoodsDetailActivity.class);
                intent.putExtra(GoodsDetailActivity.EXTRA_GOODS_ID,goods.goods_id);
                getContext().startActivity(intent);
            }
        });

        /**侧滑删除*/
        sml_swipe.setSwipeEnable(swipe);
        if (swipe){
            btn_delete.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onDeleteGoods !=null){
                        onDeleteGoods.delete(goods);
                    }
                }
            });
        }

        return view;
    }

    private int layout(){
        return editable?R.layout.layout_shopping_edit:R.layout.layout_shopping;
    }

    /**编辑购物车*/
    private void onEditGoods(View view,final Goods goods){
        final TextView tv_number = (TextView) view.findViewById(R.id.tv_number);
        TextView tv_sub = (TextView) view.findViewById(R.id.tv_sub);
        TextView tv_plus = (TextView) view.findViewById(R.id.tv_plus);
        final TextView tv_attr = (TextView) view.findViewById(R.id.tv_attr);

        tv_number.setText(String.valueOf(goods.goods_number));

        tv_attr.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mOnAttrClickListener !=null) {
                    mOnAttrClickListener.onAttrClick(goods);
                }
            }
        });

        tv_sub.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (goods.goods_number <= 1) {
                    return;
                }
                goods.goods_number--;
                goods.shopping_change = true;
                tv_number.setText(String.valueOf(goods.goods_number));

            }
        });

        tv_plus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                goods.goods_number++;
                if (goods.goods_number > goods.stock_number) {
                    goods.goods_number = goods.stock_number;
                    toast(goods);
                }
                goods.shopping_change = true;
                tv_number.setText(String.valueOf(goods.goods_number));
            }
        });
    }

    private void toast(Goods goods){
        Toast.makeText(getContext(),String.format(goods_inventory_shortage,goods.stock_number),Toast.LENGTH_SHORT).show();
    }

    private boolean isCheckAll(){
        for (CheckBox cb:checkBoxes){
            if (!cb.isChecked()){
                return false;
            }
        }
        return true;
    }

    private String toAttr(List<AttrItem> attrItems){
        if (EUtils.isEmpty(attrItems)){
            return "";
        }

        StringBuilder sb = new StringBuilder();
        boolean hasMore = false;
        for (AttrItem item:attrItems){
            sb.append(hasMore?" ":"");
            sb.append(item.attr_name).append(":").append(item.attr_value);
            hasMore = true;
        }
        return sb.toString();
    }

    public void check(boolean check){
        for (CheckBox cb:checkBoxes){
            cb.setChecked(check);
        }
    }

    public ShoppingView setAttrListener(OnAttrClickListener onAttrClickListener) {
        this.mOnAttrClickListener = onAttrClickListener;
        return this;
    }
    private OnAttrClickListener mOnAttrClickListener;
    public interface OnAttrClickListener{
        void onAttrClick(Goods goods);
    }

    public ShoppingView setOnDeleteGoods(ShoppingAdapter.OnDeleteGoods onDeleteGoods) {
        this.onDeleteGoods = onDeleteGoods;
        return this;
    }

    private ShoppingAdapter.OnDeleteGoods onDeleteGoods;

}
